#ifndef DEMO_H
#define DEMO_H

#include "Sound.h"
#include "Engine.h"

using namespace Cvekas;

class Demo;

class TimelineSegment
{
public:
	TimelineSegment() { Engine e; video_device = e.getVideoDevice(); };
	virtual ~TimelineSegment() {};

	virtual void init(boost::weak_ptr<Demo> owner) = 0;
	virtual void close() = 0;
	virtual void update(float t) {};
	virtual void render(float t) {};

protected:
	boost::weak_ptr<Demo> owner;
	VideoDevicePtr video_device;
};

typedef boost::shared_ptr<TimelineSegment> TimelineSegmentPtr;

class Demo : public boost::enable_shared_from_this<Demo>
{
public:
	Demo(SoundPtr soundtrack);
	virtual ~Demo();

	void add(int priority, float start, float end, TimelineSegmentPtr segment);
	void seal();
		
	float getTime();
	void setTime(float t);

	float getCurrentSegmentLength();

	void pause();
	void play();

	bool update();
	bool render();

private:
	
	struct DemoSegment
	{
		int priority;
		float start, end;
		TimelineSegmentPtr segment;

		bool operator<(const DemoSegment& s) const
		{
			return start < s.start;
		}
	};

	float start_time;
	static const uint max_active_segments = 8;

	uint gatherActiveSegments(float t, DemoSegment out[]);
	static bool comparePriorities(const DemoSegment& s1, const DemoSegment& s2);
	
	std::vector<DemoSegment> segments;
	float time;
	float last_gather;
	float current_segment_length;

	SoundPtr soundtrack;
};

typedef boost::shared_ptr<Demo> DemoPtr;

inline float transformT(float start, float end, float t)
{
	return (t - start) / (end - start);
}

#endif